#!/usr/bin/python
# -*- coding: utf-8 -*-
import maya.cmds as mc
import sys
import maya.mel as mel
import re

import tools_Persional.LZ_Tools.LZ_command.LZ_rivet
reload(tools_Persional.LZ_Tools.LZ_command.LZ_rivet)
#import tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mayaPrint
#tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mayaPrint.MayaPrint,


import tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mesh

class LZ_ToolsCommands(tools_Persional.LZ_Tools.LZ_command.LZ_rivet.LZ_rivet,
                        tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mesh.MeshShape):
    def fixCtrls(self):
        rivetObj=mc.textFieldButtonGrp('FixedCtrls',q=True, text=True)
        IFrotate=mc.checkBox('rotate',q=True,v=True)
        IFMO=mc.checkBox('maintainOffset',q=True,v=True)
        self.fixedCtrl(rivetObj,IFrotate,IFMO)
        
    #----------------------------------------------
    
    def createRecerseJoint(self):
        
        stept=mc.intSliderGrp('createReversejnt',q=True,value=True)
        self.createRecerseJnt(stept)
    def conReverseAttr(self):
        skinname=mc.textFieldGrp('conneReverseAttr',q=True, text=True)
        IsAllCluters=mc.checkBox('all',q=True,v=True)
        self.conneReverseAttr(skinname,IsAllCluters)
        
    
    def nzgLoadObj(self):
        meshname=mc.ls(sl=True)[0]

        mc.textFieldButtonGrp('centerObj',e=True, text=meshname)
        
    def suffixMZG(self):
        seleobjects=mc.ls(sl=True)
        
        suffixName=mc.textFieldGrp('MZGSuffix',q=True, text=True)
        
        modeOption=mc.radioButtonGrp('addMode',q=True,sl=True)
        centerObject=mc.textFieldButtonGrp('centerObj',q=True, text=True)
        modeOption=modeOption-1
        self.makeZeroGrpTwo(sufname=suffixName,cenObj=centerObject,Mode=modeOption)
        sys.stdout.write('centerObject')
        mc.select(seleobjects)
        
    def sequenceParent(self):
        objsel=mc.ls(sl=True)
        mountsobj=len(objsel)
        for i in range(mountsobj-1):
            mc.parent(objsel[i],objsel[i+1])
            
            
    def getPoleVector(self):
        #get ikhandle if you selected.
        ikhs = mc.ls(sl=True)
        sequencenum=0
        if len(ikhs)<=0:
                mc.error('You must select a ikhandle first !')

        for ikh in ikhs:
            
            startJnt = mc.listConnections(str(ikh)+'.startJoint' , p=False)
            elbowORkneeJnt = mc.listRelatives(startJnt[0],ad=1,type='joint')
            elbowORkneeJnt.reverse()
            startJntPos = mc.joint(elbowORkneeJnt[0],q=True,p=True)
            
            #get poleVector date.        
            poleVecX = mc.getAttr(str(ikh)+'.poleVectorX')*1
            poleVecY = mc.getAttr(str(ikh)+'.poleVectorY')*1
            poleVecZ = mc.getAttr(str(ikh)+'.poleVectorZ')*1
            
            #  create locator
            mc.spaceLocator(n=ikhs[sequencenum]+'_locator_temple'+str(sequencenum))
            mc.move(startJntPos[0],startJntPos[1],startJntPos[2],ikhs[sequencenum]+'_locator_temple'+str(sequencenum))
            mc.spaceLocator(n=ikhs[sequencenum]+'_aimlocator_temple'+str(sequencenum))
            mc.move(startJntPos[0]+poleVecX,startJntPos[1]+poleVecY,startJntPos[2]+poleVecZ,ikhs[sequencenum]+'_aimlocator_temple'+str(sequencenum))
            mc.aimConstraint(ikhs[sequencenum]+'_aimlocator_temple'+str(sequencenum),ikhs[sequencenum]+'_locator_temple'+str(sequencenum),worldUpType='object',worldUpObject=startJnt[0])
            mc.delete(ikhs[sequencenum]+'_aimlocator_temple'+str(sequencenum))
            sequencenum=sequencenum+1
            print(sequencenum)
            
    #########################################################################################################
    ####------------------------------  no prefix reference  ---------------------------------------------
    def NoPreReference(self):
        fileName=mc.fileDialog2(fm=1,okc= 'Reference' ,cap='Reference',ff='mayaAscii (*.ma *.MA);;mayaBinary (*.mb *.MB);;mel (*.mel *.MEL);;OBJ (*.obj *.OBJ);;audio (*.wav *.WAV *.aif *.AIF *.aiff *.AIFF *.aifc *.AIFC *.mp3 *.MP3 *.snd *.au *.AU *.SND *.sd2 *.SD2 *.mov *.MOV *.qt *.QT);;move (*.mov *.MOV);;EPS (*.eps);;Adobe(R) Illustrator(R) (*.ai);;image (*.als *.ALS *.jpeg *.JPEG *.jpg *.JPG *.pntg *.PNTG *.ps *.PS *.png *.PNG *.psd *.PSD *.pict *.PICT *.qt *.QT *.qtif *.QTIF *.sgi *.SGI *.tga *.TGA *.tif *.TIF *.bmp *.BMP *.tiff *.TIFF *.iff *.IFF *.rgb *.RGB *.tdi *.TDI *.gif *.GIF *.exr *.EXR);;fluidCache (*.mcfi *.mcfp );;editMA (*.editMA);;editMB (*.editMB);;ASS (*.ass);;studioImport (*.wire);;JT_DC (*.jt);;PTC_DC (*.prt.* *.asm.* *.g);;SPF_DC (*.wire);;STEP_DC (*.stp *.step);;STL_DC (*.stl *.stla *.stlb);;SW_DC (*.sldprt *.sldasm);;IV_DC (*.iv);;CSB_DC (*.csb);;IGES_DC (*.iges *.igs);;DWG_DC (*.dwg);;DXF_DC (*.dxf);;CATIAV4_DC (*.model *.mdl *.session *.exp *.dlv *.dlv3 *.dlv4);;CATIAV5_DC (*.catproduct *.catpart *.cgr);;IPT_DC (*.ipt *.iam);;Maya Scene (*.mb *.ma *.MB *.MA);;video (*.avi *.AVI);;plug-in (*.mll *.so *.py *.pyc *.MLL *.SO *.PY *.PYC *.bundle *.BUNDLE);;text (*.txt *.TXT);;Best Guess (*.*);;ag (*.ag *.AG);;iff (*.iff *.IFF);;From Tool Settings (*.*);;Maya IFF (*.iff);;QuickTime Movie (*.qt);;MacPaint (*.pntg);;Photoshop (*.psd);;PNG (*.png);;JPEG (*.jpg);;QuickDraw (*.pict);;QuickTime Image (*.qtif);;SGI (*.sgi);;Targa (*.tga);;Tiff (*.tif);;Windows Bitmap (*.bmp);;EXR (*.EXR *.exr)')[0]
        referenceMel='referenceFile "'+fileName+'" "Best Guess";'
        mel.eval(referenceMel)


    
    
    ###############################################################################################
    
        
    #-----------------------------------------------------------------------------------------------------------------------
    #=======================================================================================================================
    
    def adjustCurveScale(self):
        scaleValue=mc.floatField('scaleCtrls',value=True,q=True)
        objsel=mc.ls(sl=True)
        for i in objsel:
            self.LZ_scaleCurveHull(i,scaleValue,scaleValue,scaleValue)
        mc.select(objsel)
    def addScale(self):
            currentValue=mc.floatField('scaleCtrls',q=True, value=True )
            modiBalue=mc.floatField('scaleCtrlsModiBalue', q=True,value=True)
            ToValue=currentValue+modiBalue
            mc.floatField('scaleCtrls',e=True,value=ToValue )
    
    def minusScale(self):
            currentValue=mc.floatField('scaleCtrls',q=True, value=True )
            modiBalue=mc.floatField('scaleCtrlsModiBalue', q=True,value=True)
            ToValue=currentValue-modiBalue
            mc.floatField('scaleCtrls',e=True,value=ToValue )

    def mirrorCurveControl_baseOnSet(self,OriPre,mirrorPre,AxisMirror):
        selectCtrlSet = mc.ls(sl=True)
        if selectCtrlSet == []:
            print('please select a set in scene')
        else:
            ctrlSet = selectCtrlSet[0]
            if mc.nodeType(ctrlSet)!='objectSet':
                print('please select a set in scene')
            else:
                tempList = mc.sets(ctrlSet,q=True)
                curves = []

                for obj in tempList:
                
                    shapes=mc.listRelatives(obj,s=True)
                    if shapes!=None:
                        for shape in shapes:
                            if mc.nodeType(shape)=='nurbsCurve' and obj not in curves:
                                
                                curves.append(obj)
                            elif mc.nodeType(shape)!='nurbsCurve' and obj in curves:
                                curves.remove(obj)
                                
                    
                if AxisMirror==1:
                    AxisInfo=[-1,1,1]
                if AxisMirror==2:
                    AxisInfo=[1,-1,1]
                if AxisMirror==3:
                    AxisInfo=[1,1,-1]
                    
                for cur in curves:
                    if OriPre in cur:
                        R_obj=cur.replace(OriPre,mirrorPre)
                        
                        if mc.objExists(R_obj)==True:
                            objshape=mc.listRelatives(cur,s=True)
                            R_objshape=mc.listRelatives(R_obj,s=True)
                            
                            if len(objshape)==len(R_objshape):
                                for shapenum in range(len(objshape)):
                                    form =    mc.getAttr(objshape[shapenum]+'.form')
                                    spans =   mc.getAttr(objshape[shapenum]+'.spans')
                                    degrees = mc.getAttr(objshape[shapenum]+'.degree')
                                    
                                    numCv=len(mc.ls(shape+'.cv[*]',fl = True))
                                    for i in range(numCv+2):
                                        pos= mc.xform(objshape[shapenum]+'.cv['+str(i)+']',q = True,ws = True,t = True)
                                        mc.xform(R_objshape[shapenum]+'.cv['+str(i)+']',t = (pos[0]*AxisInfo[0],pos[1]*AxisInfo[1],pos[2]*AxisInfo[2]),ws = True)
    def LZ_mirrorSelected(self,AxisMirror):
        objsel=mc.ls(sl=True)
        
        if AxisMirror==1:
            AxisInfo=[-1,1,1]
        if AxisMirror==2:
            AxisInfo=[1,-1,1]
        if AxisMirror==3:
            AxisInfo=[1,1,-1]
        if len(objsel)==2:        

            objshape=mc.listRelatives(objsel[0],s=True)
            R_objshape=mc.listRelatives(objsel[1],s=True)
            
            if len(objshape)==len(R_objshape):
                for shapenum in range(len(objshape)):
                    form =    mc.getAttr(objshape[shapenum]+'.form')
                    spans =   mc.getAttr(objshape[shapenum]+'.spans')
                    degrees = mc.getAttr(objshape[shapenum]+'.degree')
                    
                    numCv=len(mc.ls(str(objshape[shapenum])+'.cv[*]',fl = True))
                    for i in range(numCv+2):
                        pos= mc.xform(objshape[shapenum]+'.cv['+str(i)+']',q = True,ws = True,t = True)
                        mc.xform(R_objshape[shapenum]+'.cv['+str(i)+']',t = (pos[0]*AxisInfo[0],pos[1]*AxisInfo[1],pos[2]*AxisInfo[2]),ws = True)
            
    ########################################################################################################################
    ####                                function:      rotateOrder
    ####                                date : 2013 /08 /05
    ####                                author : lizhi
    
    def rotateOrderWindow(self):
        rotateOrderWindow = 'rotateOrderWindow'
        if mc.window(rotateOrderWindow,ex = True):
            mc.deleteUI(rotateOrderWindow)
        
        mc.window(rotateOrderWindow,widthHeight=(300, 200),t='rotate Order Window_v1.01',menuBar = True,rtf=True,s=True)

        mc.rowColumnLayout('Main',numberOfColumns=1,w=300,cal = (5,'center'),m=True)
        mc.button('add rotateOrder',c=lambda *args:self.addRotateOrder())
        mc.rowColumnLayout('orderLout',numberOfColumns=2,w=300,cal = (5,'center'),m=True)
        mc.optionMenu('OrderMenu',label='',w=150,h=30)
        

        mc.menuItem( label='xyz' )
        mc.menuItem( label='yzx' )
        mc.menuItem( label='zxy' )
        mc.menuItem( label='xzy' )
        mc.menuItem( label='yxz' )
        mc.menuItem( label='zyx' )
        
        mc.button(l='change defaultValue',w=150,c= lambda *args:self.setDV())

        mc.showWindow()
    #rotateOrderWindow()
        
    def addRotateOrder(self):
        slobj=mc.ls(sl=True)
        for i in slobj:
            mc.addAttr(i,ln='rotate_order',at='enum',en='xyz:yzx:zxy:xzy:yxz:zyx:',k=True)
            mc.connectAttr(str(i)+'.rotate_order',str(i)+'.rotateOrder')
    def setDV(self):
        slobj=mc.ls(sl=True)
        selValue=mc.optionMenu('OrderMenu',q=True,sl=True)
        for i in slobj:
            mc.addAttr(str(i)+'.rotate_order',e=True,dv=selValue-1)
    
    
    ########################################################################################################################
    #------------------------------------  threeSpanLegRig  ----------------------------------------------------------------
    def importObj(self):

            nameSpace = mc.textFieldGrp('threeSpanLegTextFG',q=True,text=True)
         
            if 'left' not in nameSpace and 'Left' not in nameSpace:
                    mc.error(" this rig tool only support rig file from left , so you namespace must includ 'left' or 'Left' .")
         
            filePath = mc.fileDialog(t='import')
         
            if len(nameSpace) == 0:
                    mc.error('---->>>>you should enter a nameSpace !<<<<----')
            else:
                    mc.file(filePath,i=True,ns=nameSpace)
                    
    def threeSpanLegFinal_cmd(self):

            mirror=mc.checkBoxGrp('legMirror',q=True,value=True)
            prefix = mc.textFieldGrp('threeSpanLegTextFG',q=True,text=True)
    
            if mirror == False:
                    orcj.createSpaceJnt('threeSpan' , 'off' , prefix)
                    orcj.createSpaceJnt('foot' , 'off' , prefix)
                    orrsl.rigThreeSpanleg(prefix)
    
            elif mirror == True:
                    orcj.createSpaceJnt('threeSpan' , 'on' , prefix)
                    orcj.createSpaceJnt('foot' , 'on' , prefix)
    
                    if 'left'in prefix:
                            mirrorPrefix = prefix.replace('left','right')
                            orrsl.rigThreeSpanleg(prefix)
                            orrsl.rigThreeSpanleg(mirrorPrefix)
                    elif 'Left' in prefix:
                            mirrorPrefix = prefix.replace('Left','Right')
                            orrsl.rigThreeSpanleg(prefix)
                            orrsl.rigThreeSpanleg(mirrorPrefix)
    def replaceUV(self,delRefObj=True,printer=True):
            sels=mc.ls(sl=1,ap=1)
            isRefs = mc.referenceQuery(sels[0],isNodeReferenced=1)
            if len(sels)!=2:#how many objs selected
                    self.mayaError("No 2 objects select.")
                    return False
            if self.meshCompare(sels[0],sels[1])!=True:#check two object weather has equal topology
                    self.mayaWarning("Topology %s != %s."%(sels[0],sels[1]))
                    return False
            #funtion main
            #make objShape as current
            tempObjForRepShape = mc.createNode('mesh')
            tempObjForRep = mc.listRelatives(tempObjForRepShape,p=True)
            mc.connectAttr("%s.outMesh"%(sels[0]),"%s.inMesh"%(tempObjForRepShape))
            lisHis = mc.listHistory(sels[1],il=1,pdo=1)
            if lisHis!=None:#has shapeOrig
                    atrList = []
                    #set all of its deformer envelope zero
                    for x in lisHis:
                            if mc.objExists("%s.envelope"%(x)):
                                    oriValue = mc.getAttr("%s.envelope"%(x))
                                    atrList.append(oriValue)
                                    mc.setAttr("%s.envelope"%(x),lock=False)
                                    mc.setAttr("%s.envelope"%(x),0)
                    mc.blendShape(sels[1],tempObjForRep,w=[0,1])
                    mc.delete(tempObjForRep,ch=True)
                    #set all of its deformer envelope original value
                    i=0
                    for x in lisHis:
                            if mc.objExists("%s.envelope"%(x)):
                                    mc.setAttr("%s.envelope"%(x),atrList[i])
                                    i+=1
                    #
                    self.deleteUnuseOrig(sels[1])
                    shapeOrig = self.getMeshOrig(sels[1])
                    if shapeOrig!=None:
                            objAttr = mc.listConnections("%s.worldMesh"%(shapeOrig),d=1,p=1)
                            for na in objAttr:#object name and attribute name
                                    mc.connectAttr("%s.worldMesh"%(tempObjForRepShape),na,f=True)
                                    #self.mayaPrint("%s.worldMesh-->%s"%(tempObjForRepShape,na))
                            mc.parent(tempObjForRepShape,sels[1],r=True,s=True)
                            mc.delete(shapeOrig,tempObjForRep)
                            mc.rename(tempObjForRepShape,self.getLastName(shapeOrig))
                            mc.setAttr("%s.intermediateObject"%(shapeOrig),1)
            else:#there isn't shapeOrig
                    mc.blendShape(sels[1],tempObjForRep,w=[0,1])
                    mc.delete(tempObjForRep,ch=True)
                    targetShapes = mc.listRelatives(sels[1],shapes=True,c=True)[0]
                    mc.connectAttr("%s.outMesh"%(tempObjForRepShape),"%s.inMesh"%(targetShapes))
                    #if straight delete tempObjForRep uv maby wrong so must create a deformer
                    mc.cluster(sels[1])
                    mc.delete(sels[1],ch=True)
                    mc.delete(tempObjForRep)
            mc.select(sels[1])
            if delRefObj==True and isRefs==False:
                    mc.delete(sels[0])
            if printer==True:
                    self.mayaPrint("Replace UV from %s to %s."%(sels[0],sels[1]))
            return True
    def LZ_scaleCurveHull(self,curvename,scalX,scalY,scalZ):
        curveshapes=mc.listRelatives(curvename,s=True)
        
        cvAllX=[]
        cvAllY=[]
        cvAllZ=[]

        for curveshape in curveshapes:
            spans=mc.getAttr(str(curveshape)+'.spans')
            degree=mc.getAttr(str(curveshape)+'.degree')
            pointsMounts=spans+degree

            for i in range(pointsMounts):

                pointcvPos=mc.xform(str(curveshape)+'.cv['+str(i)+']',q=True,t=True,ws=True)

                cvAllX.append(pointcvPos[0])
                cvAllY.append(pointcvPos[1])
                cvAllZ.append(pointcvPos[2])
                
        pointCVposXMin=cvAllX[0]
        pointCVposYMin=cvAllY[0]
        pointCVposZMin=cvAllZ[0]
        
        pointCVposXMax=cvAllX[0]
        pointCVposYMax=cvAllY[0]
        pointCVposZMax=cvAllZ[0]
        


        for k in range(len(cvAllX)):
            pointCVposXMin=min(pointCVposXMin,cvAllX[k])
            pointCVposXMax=max(pointCVposXMax,cvAllX[k])
            
            pointCVposYMin=min(pointCVposYMin,cvAllY[k])
            pointCVposYMax=max(pointCVposYMax,cvAllY[k])
            
            pointCVposZMin=min(pointCVposZMin,cvAllZ[k])
            pointCVposZMax=max(pointCVposZMax,cvAllZ[k])
        
        centerPivetX=(pointCVposXMin+pointCVposXMax)/2
        centerPivetY=(pointCVposYMin+pointCVposYMax)/2
        centerPivetZ=(pointCVposZMin+pointCVposZMax)/2
        
        centerPivet=[centerPivetX,centerPivetY,centerPivetZ]
            
        #mc.select(str(curvename)+'.cv[0:'+str((pointsMounts-1))+']')
        
        for curveshape in curveshapes:
            
            spans=mc.getAttr(str(curveshape)+'.spans')
            degree=mc.getAttr(str(curveshape)+'.degree')
            pointsMounts=spans+degree
            
            
            cv = str(curveshape)+'.cv[0:'+str((pointsMounts-1))+']'
            mc.scale(scalX,scalY,scalZ,cv,r=True,p=centerPivet)